package com.api.shopapi.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.config.RoleConfig;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.*;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


/**
 * 机构
 */

@RestController
@RequestMapping("Institution")
public class InstitutionController extends BaseController {

    @Autowired
    @Qualifier("InstitutionServiceImplOne")
    private InstitutionService institutionService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("RoleServiceImplOne")
    private RoleService roleService;

    @Autowired
    @Qualifier("InstitutionStaffRelServiceImplOne")
    private InstitutionStaffRelService institutionStaffRelService;


    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;


    @Autowired
    @Qualifier("MedicinerServiceImplOne")
    private MedicinerService medicinerService;


    @Autowired
    @Qualifier("NurseServiceImplOne")
    private NurseService nurseService;


    @Autowired
    @Qualifier("NurseAideServiceImplOne")
    private NurseAideService nurseAideService;


    //政府管理员获取面板数据
    @RequestMapping(value = "PannelVisual", method = RequestMethod.POST)
    public MyResult PannelVisual(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String governmentCode = jsonObject.getString("governmentCode");


            PreCheck preCheck = checkSignFrontInterface(timeStr, sign, "/Institution/PannelVisual");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<Institution> list = institutionService.listByGovCode(governmentCode);

            List<Institution> list1 = institutionService.listByGovCodeType(governmentCode, 1);
            List<Institution> list2 = institutionService.listByGovCodeType(governmentCode, 2);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("institutionCount", list.size());
            jsonObject1.put("institutionCount1", list1.size());
            jsonObject1.put("institutionCount2", list2.size());
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Institution/PannelVisual", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //列表
    @RequestMapping(value = "GovPage", method = RequestMethod.POST)
    public MyResult GovPage(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            String name = jsonObject.getString("name");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode, "/Business/PageGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<Institution> pageInfo = institutionService.pageByGovCodeName(pageIndex,
                    pageSize, staff.getGovernmentCode(), name);

            List<InstitutionDTO> listDTO = new ArrayList<>();
            for (Institution institution : pageInfo.getList()) {

                InstitutionDTO institutionDTO = mapper.map(institution, InstitutionDTO.class);

                User user = userService.getByUserCode(institution.getUserCode());
                UserDTO userDTO = mapper.map(user, UserDTO.class);
                institutionDTO.setUserDTO(userDTO);

                List<InstitutionStaffRel> listRel =
                        institutionStaffRelService.getListByInstitutionCode(institution.getInstitutionCode());
                List<InstitutionStaffRelDTO> listRelDTO = new ArrayList<>();
                for (InstitutionStaffRel institutionStaffRel : listRel) {
                    InstitutionStaffRelDTO institutionStaffRelDTO = mapper.map(institutionStaffRel, InstitutionStaffRelDTO.class);

                    Staff staff2 = staffService.getByStaffCode(institutionStaffRelDTO.getStaffCode());
                    institutionStaffRelDTO.setStaffName(staff2.getLoginName());

                    listRelDTO.add(institutionStaffRelDTO);
                }
                institutionDTO.setListInstitutionStaffRelDTO(listRelDTO);


                List<Elderly> listElderly = elderlyService.listByInsCode(institution.getInstitutionCode());
                institutionDTO.setCountElderly(listElderly.size());

                List<Mediciner> listMediciner = medicinerService.listByInsCode(institution.getInstitutionCode());
                institutionDTO.setCountMediciner(listMediciner.size());

                List<Nurse> listNurse = nurseService.listByInsCode(institution.getInstitutionCode());
                institutionDTO.setCountNurse(listNurse.size());

                List<NurseAideDTO> listNurseAide = nurseAideService.listByInsCode(institution.getInstitutionCode());
                institutionDTO.setCountNurseAide(listNurseAide.size());

                listDTO.add(institutionDTO);
            }

            PageInfo<InstitutionDTO> pageInfo1 = new PageInfo<>();
            pageInfo1.setTotal(pageInfo.getTotal());
            pageInfo1.setList(listDTO);

            return success(pageInfo1);

        } catch (Exception e) {
            insertError("/Business/PageGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "GovPage2", method = RequestMethod.POST)
    public MyResult GovPage2(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            String name = jsonObject.getString("name");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode, "/Business/PageGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<Institution> pageInfo = institutionService.pageByGovCodeName(pageIndex,
                    pageSize, staff.getGovernmentCode(), name);

            List<InstitutionDTO> listDTO = new ArrayList<>();
            for (Institution institution : pageInfo.getList()) {

                InstitutionDTO institutionDTO = mapper.map(institution, InstitutionDTO.class);

                User user = userService.getByUserCode(institution.getUserCode());
                UserDTO userDTO = mapper.map(user, UserDTO.class);
                institutionDTO.setUserDTO(userDTO);

                List<InstitutionStaffRel> listRel =
                        institutionStaffRelService.getListByInstitutionCode(institution.getInstitutionCode());
                List<InstitutionStaffRelDTO> listRelDTO = new ArrayList<>();
                for (InstitutionStaffRel institutionStaffRel : listRel) {
                    InstitutionStaffRelDTO institutionStaffRelDTO = mapper.map(institutionStaffRel, InstitutionStaffRelDTO.class);

                    Staff staff2 = staffService.getByStaffCode(institutionStaffRelDTO.getStaffCode());
                    institutionStaffRelDTO.setStaffName(staff2.getLoginName());

                    listRelDTO.add(institutionStaffRelDTO);
                }
                institutionDTO.setListInstitutionStaffRelDTO(listRelDTO);

                listDTO.add(institutionDTO);

            }

            PageInfo<InstitutionDTO> pageInfo1 = new PageInfo<>();
            pageInfo1.setTotal(pageInfo.getTotal());
            pageInfo1.setList(listDTO);

            return success(pageInfo1);

        } catch (Exception e) {
            insertError("/Business/PageGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //添加
    @RequestMapping(value = "GovAdd", method = RequestMethod.POST)
    @Transactional
    public MyResult GovAdd(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String loginName = jsonObject.getString("loginName");
            String phone = jsonObject.getString("phone");
            String password = jsonObject.getString("password");
            String name = jsonObject.getString("name");

            String lon = jsonObject.getString("lon");
            String lat = jsonObject.getString("lat");
            String address = jsonObject.getString("address");

            int type = jsonObject.getInteger("type");
            //String insLevel = jsonObject.getString("insLevel");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode, "/Institution/AddGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            User user = userService.getByLoginName(loginName);
            if (user != null) {
                return failed("登录名已注册");
            }

            String insCode = UUID.randomUUID().toString();

            user = new User();
            user.setUserCode(UUID.randomUUID().toString());
            user.setPhone(phone);
            user.setPassword(getMD5Str(password));
            user.setName(name);
            user.setCreateTime(new Date());
            user.setUserType(6);
            user.setStatus(1);
            user.setLoginName(loginName);
            user.setGovernmentCode(staff.getGovernmentCode());
            user.setInstitutionCode(insCode);
            userService.insert(user);

            Institution institution = new Institution();
            institution.setInstitutionCode(insCode);
            institution.setUserCode(user.getUserCode());
            institution.setCreateTime(new Date());
            institution.setGovernmentCode(staff.getGovernmentCode());
            institution.setLon(lon);
            institution.setLat(lat);
            institution.setAddress(address);
            institution.setType(type);
            //institution.setInsLevel(insLevel);
            institutionService.insert(institution);

            Object object = new Object[]{};
            return success(object);

        } catch (Exception e) {
            insertErrorForAffair("/Institution/AddGov!", jsonObject, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }

    }


    //编辑
    @RequestMapping(value = "GovEdit", method = RequestMethod.POST)
    @Transactional
    public MyResult GovEdit(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            int status = jsonObject.getInteger("status");

            String lon = jsonObject.getString("lon");
            String lat = jsonObject.getString("lat");
            String address = jsonObject.getString("address");
            String districtRouter = jsonObject.getString("districtRouter");
            String location = jsonObject.getString("location");

            int type = jsonObject.getInteger("type");
            //String insLevel = jsonObject.getString("insLevel");

            String institutionCode = jsonObject.getString("institutionCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode, "/Institution/EditGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Institution institution = institutionService.getByInstitutionCode(institutionCode);
            if (institution == null) {
                return failed("机构不存在");
            }

            User user = userService.getByUserCode(institution.getUserCode());
            if (user == null) {
                return failed("用户不存在");
            }

            institution.setDistrictRouter(districtRouter);
            institution.setAddress(address);
            institution.setLon(lon);
            institution.setLat(lat);
            institution.setType(type);
            institution.setLocation(location);
            //institution.setInsLevel(insLevel);
            institutionService.update(institution);


            user.setName(name);
            user.setPhone(phone);
            user.setStatus(status);
            userService.update(user);

            Object data = new Object[]{};
            return success(data);

        } catch (Exception e) {
            insertErrorForAffair("/Institution/EditGov!", jsonObject, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }

    }


    //列表
    @RequestMapping(value = "List", method = RequestMethod.POST)
    public MyResult List(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String governmentCode = jsonObject.getString("governmentCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign, "/Institution/List");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<Institution> list = institutionService.listByGovCode(governmentCode);

            List<InstitutionDTO> listDTO = new ArrayList<>();
            for (Institution institution : list) {
                InstitutionDTO institutionDTO = mapper.map(institution, InstitutionDTO.class);
                User user = userService.getByUserCode(institution.getUserCode());
                if (user != null) {
                    institutionDTO.setUserName(user.getName());
                }

                if (institution.getLat() != null && !institution.getLat().equals("")) {
                    listDTO.add(institutionDTO);
                }

            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("list", listDTO);

            return success(jsonObject1);
        } catch (Exception e) {
            insertErrorForAffair("/Institution/Info", jsonObject, e);
            return anomalous(getExceptionMsg(e));
        }

    }

    //列表
    @RequestMapping(value = "ListAll", method = RequestMethod.POST)
    public MyResult ListAll(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign, "/Institution/List");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            List<Institution> list = institutionService.listByGovCode(staff.getGovernmentCode());

            List<InstitutionDTO> listDTO = new ArrayList<>();
            for (Institution institution : list) {
                InstitutionDTO institutionDTO = mapper.map(institution, InstitutionDTO.class);
                User user = userService.getByUserCode(institution.getUserCode());
                institutionDTO.setUserName(user.getName());
                listDTO.add(institutionDTO);
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("list", listDTO);

            return success(jsonObject1);
        } catch (Exception e) {
            insertErrorForAffair("/Institution/Info", jsonObject, e);
            return anomalous(getExceptionMsg(e));
        }

    }


    //导入
    @RequestMapping(value = "AddForOut", method = RequestMethod.POST)
    public MyResult AddForOut(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            JSONArray insArray = jsonObject.getJSONArray("insArray");

            String governmentCode = "9d7bfed5-5b29-46a6-9f84-057414260669";

            if (!checkSignForOut(timeStr, sign)) {
                return failed("签名错误");
            }


            Role role = roleService.getByName(RoleConfig.institutionRoleName);

            HashMap<String, String> hashMapPhone = new HashMap<>();
            //数据的一个校验
            for (int i = 0; i < insArray.size(); i++) {

                String name = insArray.getJSONObject(i).getString("name").trim();
                String phone = insArray.getJSONObject(i).getString("phone");

                if (name.equals("")) {
                    return failed("名称不能为空");
                }
                if (!isPhone(phone)) {
                    return failed("手机格式错误");
                }

                if (hashMapPhone.containsKey(phone)) {
                    return failed("手机号存在重复的" + phone);
                } else {
                    hashMapPhone.put(phone, phone);
                }

            }

            Date date = new Date();

            for (int i = 0; i < insArray.size(); i++) {

                String name = insArray.getJSONObject(i).getString("name");
                String phone = insArray.getJSONObject(i).getString("phone");
                String lon = insArray.getJSONObject(i).getString("lon");
                String lat = insArray.getJSONObject(i).getString("lat");
                String address = insArray.getJSONObject(i).getString("address");
                int type = insArray.getJSONObject(i).getInteger("type");

                String insCode = UUID.randomUUID().toString();

                User user = userService.getByPhone(phone);
                if (user == null) {
                    user = new User();
                    user.setUserCode(UUID.randomUUID().toString());
                    user.setName(name);
                    user.setLoginName(phone);
                    user.setPhone(phone);
                    user.setPassword(getMD5Str(phone.substring(5, 11)));
                    user.setUserType(6);
                    user.setStatus(1);
                    user.setGovernmentCode(governmentCode);
                    user.setInstitutionCode(insCode);
                    user.setCreateTime(date);
                    userService.insert(user);


                    Institution institution = new Institution();
                    institution.setInstitutionCode(insCode);
                    institution.setUserCode(user.getUserCode());
                    institution.setAddress(address);
                    institution.setLat(lat);
                    institution.setLon(lon);
                    institution.setType(type);
                    institution.setGovernmentCode(governmentCode);
                    institution.setCreateTime(date);
                    institutionService.insert(institution);

                    Staff staff3 = new Staff();
                    staff3.setStaffCode(UUID.randomUUID().toString());
                    staff3.setGovernmentCode(governmentCode);
                    staff3.setInstitutionCode(insCode);
                    staff3.setRoleCode(role.getRoleCode());
                    staff3.setLoginName(phone);
                    staff3.setPassword(getMD5Str(phone.substring(5, 11)));
                    staff3.setRealName(phone);
                    staff3.setPhone(phone);
                    staff3.setCreateTime(date);
                    staffService.insert(staff3);


                    //删除老的关系
                    List<InstitutionStaffRel> listStaffRel = institutionStaffRelService.getListByInstitutionCode(insCode);
                    for (InstitutionStaffRel institutionStaffRel : listStaffRel) {
                        institutionStaffRelService.deleteByInstitutionStaffRelCode(institutionStaffRel.getInstitutionStaffRelCode());
                    }

                    //增加新的关系
                    InstitutionStaffRel institutionStaffRel = new InstitutionStaffRel();
                    institutionStaffRel.setInstitutionStaffRelCode(UUID.randomUUID().toString());
                    institutionStaffRel.setInstitutionCode(insCode);
                    institutionStaffRel.setStaffCode(staff3.getStaffCode());
                    institutionStaffRelService.insert(institutionStaffRel);

                }else{
                    user.setName(name);
                    user.setLoginName(phone);
                    user.setPhone(phone);
                    user.setGovernmentCode(governmentCode);
                    userService.updateName(user);
                    Institution institution = institutionService.getByInstitutionCode(user.getInstitutionCode());
                    institutionService.updateAddressAndLatLngAndType(institution);
                }

            }

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Instituton/AddForOut", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //获取信息
    @RequestMapping(value = "InfoByPhone", method = RequestMethod.POST)
    public MyResult InfoByPhone(@RequestBody JSONObject jsonObject) {

        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String phone = jsonObject.getString("phone");


            if (!checkSignForOut(timeStr, sign)) {
                return failed("签名错误");
            }

            User user = userService.getByPhone(phone);
            if (user == null) {
                return failed("用户不存在");
            }

            user.setPassword(null);


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("user", user);

            return success(jsonObject1);
        } catch (Exception e) {
            insertErrorForAffair("/Institution/Info", jsonObject, e);
            return anomalous(getExceptionMsg(e));
        }

    }


}
